#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
配置管理模块
管理项目的各种配置参数和环境变量
"""

import os
from dotenv import load_dotenv

class Config:
    """配置管理类"""
    
    def __init__(self, config_file=None):
        """
        初始化配置
        
        Args:
            config_file (str): 配置文件路径，默认为项目根目录的.env文件
        """
        # 加载环境变量
        if config_file:
            load_dotenv(config_file)
        else:
            load_dotenv()
        
        # 项目路径配置
        self.PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        self.RECORDINGS_DIR = os.path.join(self.PROJECT_ROOT, "recordings")
        self.TRANSCRIPTS_DIR = os.path.join(self.PROJECT_ROOT, "transcripts")
        self.SUMMARIES_DIR = os.path.join(self.PROJECT_ROOT, "summaries")
        self.BITABLE_DIR = os.path.join(self.PROJECT_ROOT, "bitable")
        
        # 确保目录存在
        self._ensure_directories()
        
        # 语音识别API配置
        self.SPEECH_API_TOKEN = os.getenv("SPEECH_API_TOKEN")
        self.SPEECH_API_URL = os.getenv("SPEECH_API_URL")
        self.SPEECH_FORMAT = os.getenv("SPEECH_FORMAT", "wav")
        self.SPEECH_SAMPLE_RATE = int(os.getenv("SPEECH_SAMPLE_RATE", "16000"))
        
        # 大模型配置
        self.LLM_API_KEY = os.getenv("API_KEY")
        self.LLM_BASE_URL = os.getenv("BASE_URL")
        self.LLM_MODEL_NAME = os.getenv("MODEL_NAME")
        self.LLM_TEMPERATURE = float(os.getenv("LLM_TEMPERATURE", "0.6"))
        self.LLM_MAX_SUMMARY_LENGTH = int(os.getenv("LLM_MAX_SUMMARY_LENGTH", "500"))
        self.LLM_MAX_TITLE_LENGTH = int(os.getenv("LLM_MAX_TITLE_LENGTH", "20"))
        
        # 飞书配置
        self.FEISHU_APP_ID = os.getenv("FEISHU_APP_ID")
        self.FEISHU_APP_SECRET = os.getenv("FEISHU_APP_SECRET")
        self.FEISHU_USER_ACCESS_TOKEN = os.getenv("FEISHU_USER_ACCESS_TOKEN")
        self.FEISHU_BITABLE_TOKEN = os.getenv("FEISHU_BITABLE_TOKEN")
        
        # 录音配置
        self.AUDIO_SAMPLE_RATE = int(os.getenv("AUDIO_SAMPLE_RATE", "44100"))
        self.AUDIO_CHANNELS = int(os.getenv("AUDIO_CHANNELS", "1"))
        self.AUDIO_FORMAT = os.getenv("AUDIO_FORMAT", "wav")
        
        # 自动化流程配置
        self.AUTO_PROCESS_ENABLED = os.getenv("AUTO_PROCESS_ENABLED", "true").lower() == "true"
        self.AUTO_PUSH_TO_FEISHU = os.getenv("AUTO_PUSH_TO_FEISHU", "true").lower() == "true"
        self.DELETE_TEMP_FILES = os.getenv("DELETE_TEMP_FILES", "false").lower() == "true"
        
        # 验证必要的配置
        self._validate_config()
    
    def _ensure_directories(self):
        """确保所有必要的目录存在"""
        directories = [
            self.RECORDINGS_DIR,
            self.TRANSCRIPTS_DIR,
            self.SUMMARIES_DIR
        ]
        
        for directory in directories:
            os.makedirs(directory, exist_ok=True)
    
    def _validate_config(self):
        """验证必要的配置是否存在"""
        required_configs = {
            "SPEECH_API_TOKEN": self.SPEECH_API_TOKEN,
            "SPEECH_API_URL": self.SPEECH_API_URL,
            "LLM_API_KEY": self.LLM_API_KEY,
            "LLM_BASE_URL": self.LLM_BASE_URL,
            "LLM_MODEL_NAME": self.LLM_MODEL_NAME
        }
        
        missing_configs = []
        for config_name, config_value in required_configs.items():
            if not config_value:
                missing_configs.append(config_name)
        
        if missing_configs:
            print(f"警告：以下配置缺失，可能影响功能正常使用：")
            for config in missing_configs:
                print(f"  - {config}")
            print("请在.env文件中设置这些配置项")
    
    def get_audio_file_path(self, filename):
        """
        获取录音文件的完整路径
        
        Args:
            filename (str): 文件名
            
        Returns:
            str: 完整文件路径
        """
        return os.path.join(self.RECORDINGS_DIR, filename)
    
    def get_transcript_file_path(self, filename):
        """
        获取转录文件的完整路径
        
        Args:
            filename (str): 文件名
            
        Returns:
            str: 完整文件路径
        """
        return os.path.join(self.TRANSCRIPTS_DIR, filename)
    
    def get_summary_file_path(self, filename):
        """
        获取摘要文件的完整路径
        
        Args:
            filename (str): 文件名
            
        Returns:
            str: 完整文件路径
        """
        return os.path.join(self.SUMMARIES_DIR, filename)
    
    def print_config(self):
        """打印当前配置信息"""
        print("=== 项目配置信息 ===")
        print(f"项目根目录: {self.PROJECT_ROOT}")
        print(f"录音目录: {self.RECORDINGS_DIR}")
        print(f"转录目录: {self.TRANSCRIPTS_DIR}")
        print(f"摘要目录: {self.SUMMARIES_DIR}")
        print(f"飞书模块目录: {self.BITABLE_DIR}")
        print()
        print("=== 语音识别配置 ===")
        print(f"模型: {self.SPEECH_MODEL}")
        print(f"格式: {self.SPEECH_FORMAT}")
        print(f"采样率: {self.SPEECH_SAMPLE_RATE}")
        print(f"语言提示: {self.SPEECH_LANGUAGE_HINTS}")
        print()
        print("=== 大模型配置 ===")
        print(f"模型名称: {self.LLM_MODEL_NAME}")
        print(f"温度参数: {self.LLM_TEMPERATURE}")
        print(f"最大摘要长度: {self.LLM_MAX_SUMMARY_LENGTH}")
        print(f"最大标题长度: {self.LLM_MAX_TITLE_LENGTH}")
        print()
        print("=== 自动化配置 ===")
        print(f"自动处理启用: {self.AUTO_PROCESS_ENABLED}")
        print(f"自动推送飞书: {self.AUTO_PUSH_TO_FEISHU}")
        print(f"删除临时文件: {self.DELETE_TEMP_FILES}")

# 创建全局配置实例
config = Config()

def get_config():
    """获取配置实例"""
    return config

if __name__ == "__main__":
    # 测试配置
    config = Config()
    config.print_config()